<?php
class Translate extends Controller {
	public function __construct() {
		parent::Controller();
	}

	public function index($language) {
		echo '<pre>';
		echo "language: $language\n\n";

		$index = 5;
		$count = $this->uri->total_segments();
		$view = ''; $folder = ''; $prefix = '';

		for(; $index <= $count; $index++) {
			$view .= '/'.$this->uri->segment($index);
				
			if ($index > 5 && $index < $count)
			$prefix .= '.';
				
			if ($index < $count) {
				$folder .= '/'.$this->uri->segment($index);
				$prefix .= $this->uri->segment($index);;
			}
		}

		if ($folder == '')
		  $folder = $view;

		  
		$viewfile = APPPATH.'views'.$view.'.php';
		echo 'view: '.$viewfile.'<br/>';
		echo "exists? ".(file_exists($viewfile)? "yes" : "no")."\n\n";

		$langfile = APPPATH."language/$language$folder"."_lang.php";
		echo 'lang: '.$langfile.'<br/>';
		echo "exists? ".(file_exists($langfile)? "yes" : "no")."\n\n";

		$targetf = '/tmp'.$folder.'_lang.php';
		echo 'target: '.$targetf."\n";
		echo "exists? ".(file_exists($targetf)? "yes" : "no")."\n\n";

		echo "prefix: $prefix\n";

		$structure = substr($targetf, 0, strrpos($targetf, '/'));
		echo "prefix: $structure\n\n";

		$contents = file_get_contents($viewfile, true);

		if (file_exists($langfile)) {
			include_once $langfile;
		}

		$buffer = "<?php\n";
		$keysdone = array();

		if (preg_match_all("/lang\('[^']+/", $contents, $matches)) {

			sort($matches[0]);

			foreach ($matches[0] as $m) {
				if (!in_array($m, $keysdone)) {
					$m = str_replace("lang('", '', $m);
					$v = str_replace("$prefix.", '', $m);
					$v = str_replace('_', ' ', $v);

					if (isset($lang[$m])) {
						$buffer .= '$lang[\''.$m.'\']='."'".$lang[$m]."';\n";
					}
					else {
						echo 'New - $lang[\''.$m.'\']='."'".$v."';<br/>";
						$buffer .= '$lang[\''.$m.'\']='."'".$v."';\n";
					}

					array_push($keysdone, $m);
				}
			}
		}

		$buffer .= '?>';

		
		if (!file_exists($structure) && !mkdir($structure, 0777, true)) {
			die('Failed to create folders...');
		}

		$fh = fopen($targetf, 'w') or die("can't open file");
		fwrite($fh, $buffer);
		fclose($fh);

		echo "finished! \n";
		echo '</pre>';
	}
}
?>